/*--
 * XML.cs: Provides common utility functions for manipulating XML.
 *--
 * For more information, please visit the Metashell Project site:
 *   http://code.google.com/p/metashell/
 *--
 * (c) 2006 Christopher E. Granade.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; exactly version 2
 * of the License applies to this software.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

using System;
using System.IO;
using System.Xml;

namespace Metashell.Core.Utility {

	/// <summary>
	/// Provides utility methods for manipulating XML and Metadoc documents.
	/// </summary>
	public static class XML {
	
		/// <summary>
		/// Loads an XML file from a given path.
		/// </summary>
		/// <param name="path">Path to load a file from.</param>
		/// <returns>An XmlDocument representing the file.</returns>
		public static XmlDocument LoadXMLFromFile(string path) {
			
			XmlDocument outdoc = new XmlDocument();
			FileStream fs = new FileStream(path, FileMode.Open);
			outdoc.Load(fs);
			fs.Close();
			
			return outdoc;
			
		}
		
		/// <summary>
		/// Returns a Metadoc representing a null XmlDocument.
		/// </summary>
		public static Metadoc NullDocument {
			get {
				Metadoc d;
				d.data = null;
				d.format = MetadocFormats.Null;
				
				return d;
			}
		}
		
		/// <summary>
		/// Wraps a plaintext string into an XML document.
		/// Useful for porting legacy commands.
		/// </summary>
		/// <param name="toencap">String to be encapsulated.</param>
		/// <returns>A Metadoc with <c>format == MetadocFormats.PlainText</c>, and with
		/// 	the <c>data</c> field containing the document encapsulating the string.</returns>
		public static Metadoc EncapsulateString(string toencap) {
			
			Metadoc outdoc;
			
			if (toencap == null) {
				return XML.NullDocument;
			}
			
			outdoc.data = new XmlDocument();
			
			XmlElement xe =
				outdoc.data.CreateElement("pt", "plaintext", MetadocNamespaces.PlainText);
			XmlText xt = outdoc.data.CreateTextNode(toencap);
			xe.AppendChild(xt);
			
			outdoc.data.AppendChild(xe);
			outdoc.format = MetadocFormats.PlainText;			

			return outdoc;
			
		}
		
	}
	
}